(function($) {

var plugin = $.CommentsPlugin = {
	//Nom de la classe à instancier /!\ CE NOM DOIT ETRE UNIQUE ET IDENTIQUE AU NOM JQUERY /!\
	name: 'CommentsPlugin'
};

//Constructeur
var CommentsPlugin = function(options){ // rajouter element
	if(arguments.length) {
		this._init( options );// rajouter element
	} else 
		console.log('Aucun paramètre reçu pour CommentsPlugin');
};

CommentsPlugin.prototype = {
	defaults: {
		options:{},	
		thread_id: '',
		thread_api: '',
		script: '',
	},
	
	_init: function(options){// rajouter element
		var t = this;
		
		// Public
		t.element = $(options.element);
		t.options = $.extend(true, {}, t.defaults, options);
		t.element = (typeof t.options.element != 'undefined') ? t.options.element : null;
		t.idEvent = (typeof t.options.idEvent != 'undefined') ? t.options.idEvent : 0;
		
		$(t.element).html(t.options.content);
		
		// thread id
		window.fos_comment_thread_id = t.options.thread_id;
		
		// api base url to use for initial requests
		window.fos_comment_thread_api_base_url = t.options.thread_api;
		
		window.fos_comment_thread_container = $('#fos_comment_thread ul.thumbnails');
		
		// Snippet for asynchronously loading the comments
		var fos_comment_script = document.createElement('script');
	    fos_comment_script.async = true;
	    fos_comment_script.src = t.options.script;
	    fos_comment_script.type = 'text/javascript';
	    console.log(t.options);
	    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(fos_comment_script);
	}	
};

$.fn.pluginComments = function(options) {

	var isMethodCall = typeof options === "string",
		args = Array.prototype.slice.call( arguments, 1 ),
		returnValue = this;

	// prevent calls to internal methods
	if ( isMethodCall && options.charAt( 0 ) === "_" ) {
		return returnValue;
	}

	if ( isMethodCall ) {
		this.each(function() {
			var instance = $.data( this, 'CommentsPlugin' ),
				methodValue = instance && $.isFunction( instance[options] ) ?
					instance[ options ].apply( instance, args ) :
					instance;

			if ( methodValue !== instance && methodValue !== undefined ) {
				returnValue = methodValue;
				return false;
			}
		});
	} else {
		this.each(function() {
			var instance = $.data( this, 'CommentsPlugin' );
			if ( !instance ) {
				$.data( this, 'CommentsPlugin', new CommentsPlugin( this, options ) );
			}
		});
	}

	return returnValue;
};

// Association en tant que plugin jQuery
//$.fn.CommentsPlugin = plugin.CommentsPlugin;

// Si l'eventManager a été déclaré on le surcharge pour la gestion du plugin
if(typeof $.eventManager != 'undefined'){
	var em = $.eventManager;
	
	// Ajout du plugin au register du manager, il sera instancié par le manager automatiquement
	em.addPluginToRegister('CommentsPlugin', CommentsPlugin);
}

})(jQuery);